package com.ad.aidai.common;

import rx.Observable;
import rx.Subscriber;
import rx.subjects.PublishSubject;

/**
 * RxBus
 * <p>
 * Created by Yusxon on 16/11/26.
 */

public class RxBus {

    private static volatile RxBus sInstance;

    private RxBus() {
    }

    public static RxBus getInstance() {
        if (sInstance == null) {
            synchronized (RxBus.class) {
                if (sInstance == null) {
                    sInstance = new RxBus();
                }
            }
        }
        return sInstance;
    }

    private PublishSubject<Object> mEventBus = PublishSubject.create();

    public void postEvent(Object event) {
        mEventBus.onNext(event);
//        Logger.t("RxBus").i("onNext:" + event);
    }

    public Observable<Object> toObservable() {
        return mEventBus;
    }

    /**
     * A simple logger for RxBus which can also prevent
     * potential crash(OnErrorNotImplementedException) caused by error in the workflow.
     */
    public static Subscriber<Object> defaultSubscriber() {
        return new Subscriber<Object>() {
            @Override
            public void onCompleted() {
                //                Logger.t("RxBus").i("Completed!");
            }

            @Override
            public void onError(Throwable e) {
                //                Logger.t("RxBus").e("Error:" + e);
                e.printStackTrace();
            }

            @Override
            public void onNext(Object o) {
                //                Logger.t("RxBus").i("onNext:" + o);
            }
        };
    }
}
